% 读取图像并灰度化
image = imread('pic_original.png'); % 替换为你的图像路径
gray_image = (image);

% 定义种子点 (手动选择或通过预处理)
seed_x = 100; % 横坐标
seed_y = 150; % 纵坐标
seed_value = gray_image(seed_y, seed_x); % 种子点的灰度值

% 定义阈值（相似性判定）
threshold = 100; % 灰度值差异阈值

% 初始化区域生长
region = false(size(gray_image)); % 区域掩码
region(seed_y, seed_x) = true; % 标记种子点
queue = [seed_y, seed_x]; % 队列初始化

% 区域生长算法
while ~isempty(queue)
    % 弹出当前点
    current_point = queue(1, :);
    queue(1, :) = [];
    y = current_point(1);
    x = current_point(2);
    
    % 遍历邻域 (上下左右)
    for dy = -1:1
        for dx = -1:1
            if abs(dy) + abs(dx) > sqrt(2) % 仅考虑 4 邻域
                continue;
            end
            ny = y + dy;
            nx = x + dx;
            % 检查边界
            if ny > 0 && ny <= size(gray_image, 1) && nx > 0 && nx <= size(gray_image, 2)
                % 判断像素是否已被标记且相似
                if ~region(ny, nx) && abs(double(gray_image(ny, nx)) - double(seed_value)) <= threshold
                    region(ny, nx) = true; % 标记区域
                    queue = [queue; ny, nx]; % 加入队列
                end
            end
        end
    end
end

% 可视化结果
region_image = gray_image; % 复制原图
region_image(region) = 255; % 高亮显示区域
imwrite(region_image, 'region_highlight.png'); % 保存区域高亮图像

% 去除阴影 (简单修正)
shadow_corrected = gray_image;
shadow_corrected(region) = shadow_corrected(region) + 50; % 增加亮度
shadow_corrected(shadow_corrected > 255) = 255; % 防止溢出
imwrite(shadow_corrected, 'shadow_corrected.png'); % 保存修正后的图像
